package com.yjhz.ruleengine.demos.web.config;

import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DroolsConfig {

    private static final String RULES_PATH = "rules/";

    @Bean
    public KieFileSystem kieFileSystem() {
        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + "orderDiscount.drl"));
        return kieFileSystem;
    }

    @Bean
    public KieContainer kieContainer() {
        final KieRepository kieRepository = getKieServices().getRepository();
        kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
    }

    @Bean
    public KieBase kieBase() {
        return kieContainer().getKieBase();
    }

    @Bean
    public KieSession kieSession() {
        return kieContainer().newKieSession();
    }

    private KieServices getKieServices() {
        return KieServices.Factory.get();
    }
}
